<?php

namespace app\admin\controller\pt;

use Carbon\Carbon;
use app\common\controller\Backend;
use app\admin\model\pt\Depart as DepartModel;
use app\admin\model\pt\Job as JobModel;
use app\admin\model\pt\Person as PersonModel;
use app\admin\model\pt\DutyList as DutyModel;
use app\common\library\Export as ExportLib;
use app\common\library\Salary as SalaryLib;
use Exception;
use think\Db;
use think\Log;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 人员薪酬
 *
 * @icon fa fa-circle-o
 */
class Salary extends Backend
{

    /**
     * Salary模型对象
     * @var \app\admin\model\pt\Salary
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pt\Salary;
        $this->view->assign("salaryModeList", $this->model->getSalaryModeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
     
    /**
     * 查看
     */
    public function statistic()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            // 重新组合计算
            $month = $this->request->get('query_date');
            if (empty($month)) {
                $month = date('Ym');
            } else {
                $month = date('Ym', strtotime($month . "-01"));
            }
            /*
            $pic = Db::name('pt_person_salary')
              ->alias("pic")
              ->join('facial_scenes scene', 'pic.scenes_id = scene.id')
              ->field('pic.ai_image, scene.title scene_title')
              ->where('pic.status', '1')
              ->where('scene.status', '0')
              ->where('scene.title', 'like', '%领导%')
              ->orderRaw('rand()')
              ->find();
             */
            /*
            $personId = 2;
            $jobId = 3;
                $salaryDatas = $this->model->where('date_id', 'like', $month.'%')
                                       ->where('salary_total', '>', 0)
                                       ->where('pt_person_id', $personId)
                                       ->where('pt_job_id', $jobId)
                                       ->select();
             */
            // 按人按岗位取出人员id和岗位id 
            $groupData = $this->model->where('date_id', 'like', $month.'%')
                                   // ->where('salary_total', '>', 0)
                                   ->where('is_cal', 1)
                                   ->group('pt_person_id, pt_job_id')
                                   ->select();
            $personIds = [];
            foreach($groupData as $p) {
                $personIds[] = $p->pt_person_id;
            }
            // 查找人员信息
            $personInfos = PersonModel::where('id', 'in', $personIds)->with('labor')->select();
            $personData = [];
            foreach ($personInfos as $p) {
                $laborName = empty($p->labor) ? '-' : $p->labor->name;
                $personData[$p->id]  = [
                    'labor_name'  => $laborName,
                    'user_type' => $p->user_type,
                    'user_name' => $p->user_name,
                    'phone' => $p->phone,
                    'id_card' => $p->id_card,
                    'bank_openname' => $p->bank_openname,
                    'bank_code' => $p->bank_code,
                ];
            }
            $monthp = $month . "01";
            $monthCarbon = Carbon::parse($monthp);
            $startDay = date('Ymd', strtotime($monthCarbon->startOfMonth()->toDateString()));
            $endDay = date('Ymd', strtotime($monthCarbon->endOfMonth()->toDateString()));
            // 按人按岗位和查询时间查询并计算
            $items = [];
            foreach ($groupData as $g) {
                $personId = $g->pt_person_id;
                $jobId = $g->pt_job_id;
                // 开始查询
                $salaryDatas = $this->model->where('date_id', 'like', $month.'%')
                                       // ->where('salary_total', '>', 0)
                                       ->where('is_cal', 1)
                                       ->where('pt_person_id', $personId)
                                       ->where('pt_job_id', $jobId)
                                       ->select();
                // 实际出勤 
                $totalActualDuration = 0;
                // 餐补 
                $totalAdded1Fee = 0;
                // 补助
                $totalAdded2Fee = 0;
                // 路费
                $totalRoadFee = 0;
                // 服务费
                $totalSeviceFee = 0;
                // 激励补贴
                $totalRewardMonth = 0;
                // 薪资
                $totalSalaryTotal = 0;
                $salaryInfos = [];
                $salaryMode = '';
                foreach ($salaryDatas as $salary) {
                    // $totalActualDuration += $salary->actual_duration;
                    $totalActualDuration += $salary->actual_calc_duration;
                    // 只计算有计算过薪水的
                    if ($salary->actual_calc_duration > 0) {
                        $totalAdded1Fee += $salary->added1_fee;
                        $totalAdded2Fee += $salary->added2_fee;
                        $totalRoadFee += $salary->road_fee;
                    }
                    $totalSeviceFee += $salary->self_sevice_fee;
                    $totalRewardMonth += $salary->reward_month;
                    $totalSalaryTotal += $salary->salary_total;
                    // $salaryInfos[$salary->date_id] = $salary->actual_duration;
                    $salaryInfos[$salary->date_id] = $salary->actual_calc_duration;
                    $salaryMode = $salary->salary_mode;
                }
                // 循环一个月的时间
                $salaryData = [];
                for ($d = $startDay; $d <= $endDay; $d++) {
                    $tmp = '-';
                    if (isset($salaryInfos[$d])) {
                        $tmp = $salaryInfos[$d];
                    }
                    $salaryData[] = $tmp;
                }
                // 组装所有数据
                $item = [];
                if (isset($personData[$personId])) {
                    $item = $personData[$personId];
                } else {
                    $item = [
                        'labor_name'  => '-',
                        'user_type' => '-',
                        'user_name' => '-',
                        'phone' => '-',
                        'id_card' => '-',
                        'bank_openname' => '-',
                        'bank_code' => '-',
                    ];
                }
                $item['depart_name'] = $g['depart_name'];
                $item['job_name'] = $g['job_name'];

                $unit = '小时';
                $unit1 = '小时';
                if ($salaryMode == 'day') {
                    $unit = '天';
                } else if ($salaryMode == 'stage') {
                    $unit = '场';
                    $unit1 = '场';
                }

                $item['total_actual_duration'] = $totalActualDuration . "" . $unit;
                $item['total_added1_fee'] = $totalAdded1Fee;
                $item['total_added2_fee'] = $totalAdded2Fee;
                $item['total_road_fee'] = $totalRoadFee;

                $item['total_sevice_fee'] = $totalSeviceFee;
                $item['total_reward_month'] = $totalRewardMonth;
                $item['total_salary_total'] = $totalSalaryTotal;

                
                $day = 1; 
                foreach ($salaryData as $s) {
                    if ($s == '-') {
                        $item['day_' . $day] = $s;
                    } else {
                        $item['day_' . $day] = $s . "" . $unit;
                    }
                    $day++;
                }

                $item['pk'] = $personId . "-" . $jobId . "-" . $month;

                $items[] = $item;
            }

            $result = array("total" => count($items), "rows" => $items);

            return json($result);
        }
        $this->view->assign('query_date', date('Y-m'));
        return $this->view->fetch();
    }

    public function detail($ids)
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $arr = explode("-", $ids);
            $personId = $arr[0];
            $jobId = $arr[1];
            $month = $arr[2];

            $limit = 100;

            $list = $this->model
                ->where($where)
                ->where('date_id', 'like', $month.'%')
                ->where('pt_person_id', $personId)
                ->where('pt_job_id', $jobId)
                // ->where('salary_total', '>', 0)
                ->where('is_cal', 1)
                ->order($sort, $order)
                ->paginate($limit);

            $items = $list->items();
            $data = [];
            foreach ($items as $item) {
                $tmp = []; 
                $tmp['date'] = date('m/d', strtotime($item['date_id']));
                $clock = '';
                if (!empty($item['clock_in'])) {
                    $clock .= date('H:i', $item['clock_in']) . '/';
                }
                if (!empty($item['clock_out'])) {
                    $clock .= date('H:i', $item['clock_out']);
                }
                if (empty($clock)) {
                    $clock = '未打卡';
                }
                $tmp['clock'] = $clock;
                $unit = '小时';
                $unit1 = '小时';
                if ($item['salary_mode'] == 'day') {
                    $unit = '天';
                } else if ($item['salary_mode'] == 'stage') {
                    $unit = '场';
                    $unit1 = '场';
                }
                $tmp['require_duration'] = $item['require_duration'] . $unit1;
                $tmp['require_calc_duration'] = $item['require_calc_duration'] . $unit1;
                $tmp['actual_duration'] = $item['actual_duration'] . $unit1;
                $tmp['actual_calc_duration'] = $item['actual_calc_duration'] . $unit;

                $tmp['salary'] = $item['salary'] . '/' .$unit;
                $tmp['added1_fee'] = $item['added1_fee'];
                $tmp['added2_fee'] = $item['added2_fee'];
                $tmp['road_fee'] = $item['road_fee'];
                $tmp['salary_total'] = $item['salary_total'];
                $tmp['id'] = $item['id'];

                $data[] = $tmp;
            }

            $result = array("total" => $list->total(), "rows" => $data);

            return json($result);
        }
        return $this->view->fetch(); 
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if ($row->salary_mode == 'stage') {
                        $params['actual_duration'] = $params['actual_calc_duration'];
                    } else {
                        $params['clock_in'] = strtotime(date('Y-m-d', strtotime($row->date_id)) . " " . $params['clock_in']);
                        $params['clock_out'] = strtotime(date('Y-m-d', strtotime($row->date_id)) . " " . $params['clock_out']);
                    }
                    $result = $row->allowField(true)->save($params);
                    // 重新计算对应记录的薪水
                    $this->salaryInfo = $row;
                    $this->personInfo = PersonModel::get($row->pt_person_id);
                    $this->salaryLib = new SalaryLib();
                    // 模拟出计算需要的duty值
                    $duty = DutyModel::get($row->duty_id);
                    if ($row->salary_mode == 'stage') {
                        $clockJson['stage'] = $params['actual_calc_duration'];
                    } else {
                        $clockJson = [$row->clock_in, $row->clock_out];
                    }
                    $duty->clock_json = json_encode($clockJson);
                    $this->calSalary($duty);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!empty($row->clock_in)) {
            $row->clock_in = date('H:i', $row->clock_in);
        } else {
            $row->clock_in = '';
        }
        if (!empty($row->clock_out)) {
            $row->clock_out = date('H:i', $row->clock_out);
        } else {
            $row->clock_out = '';
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function export()
    {
        // 重新组合计算
        $month = $this->request->get('query_date');
        if (empty($month)) {
            $month = date('Ym');
        } else {
            $month = date('Ym', strtotime($month . "-01"));
        }
        // 按人按岗位取出人员id和岗位id 
        $groupData = $this->model->where('date_id', 'like', $month.'%')
                               // ->where('salary_total', '>', 0)
                               ->where('is_cal', 1)
                               ->group('pt_person_id, pt_job_id')
                               ->select();
        $personIds = [];
        foreach($groupData as $p) {
            $personIds[] = $p->pt_person_id;
        }
        // 查找人员信息
        $personInfos = PersonModel::where('id', 'in', $personIds)->with('labor')->select();
        $personData = [];
        $userTypes = [
            'labor' => '劳务公司',
            'self'  => '自招兼职',
            'intern' => '实习生',
        ];
        foreach ($personInfos as $p) {
            $laborName = empty($p->labor) ? '-' : $p->labor->name;
            $personData[$p->id]  = [
                $laborName,
                isset($userTypes[$p->user_type]) ? $userTypes[$p->user_type] : '未知',
                $p->user_name,
                $p->phone,
                $p->id_card,
                $p->bank_openname,
                $p->bank_code,
            ];
        }
        $monthp = $month . "01";
        $monthCarbon = Carbon::parse($monthp);
        $startDay = date('Ymd', strtotime($monthCarbon->startOfMonth()->toDateString()));
        $endDay = date('Ymd', strtotime($monthCarbon->endOfMonth()->toDateString()));
        $lastDay = date('d', strtotime($monthCarbon->endOfMonth()->toDateString()));
        // 按人按岗位和查询时间查询并计算
        $items = [];
        foreach ($groupData as $g) {
            $personId = $g->pt_person_id;
            $jobId = $g->pt_job_id;
            // 开始查询
            $salaryDatas = $this->model->where('date_id', 'like', $month.'%')
                                   // ->where('salary_total', '>', 0)
                                   ->where('is_cal', 1)
                                   ->where('pt_person_id', $personId)
                                   ->where('pt_job_id', $jobId)
                                   ->select();
            // 实际出勤 
            $totalActualDuration = 0;
            // 餐补 
            $totalAdded1Fee = 0;
            // 补助
            $totalAdded2Fee = 0;
            // 路费
            $totalRoadFee = 0;
            // 服务费
            $totalSeviceFee = 0;
            // 激励补贴
            $totalRewardMonth = 0;
            // 薪资
            $totalSalaryTotal = 0;
            $salaryInfos = [];
            $salaryMode = '';
            foreach ($salaryDatas as $salary) {
                // $totalActualDuration += $salary->actual_duration;
                $totalActualDuration += $salary->actual_calc_duration;
                if ($salary->actual_calc_duration > 0) {
                    $totalAdded1Fee += $salary->added1_fee;
                    $totalAdded2Fee += $salary->added2_fee;
                }
                $totalRoadFee += $salary->road_fee;
                $totalSeviceFee += $salary->self_sevice_fee;
                $totalRewardMonth += $salary->reward_month;
                $totalSalaryTotal += $salary->salary_total;
                // $salaryInfos[$salary->date_id] = $salary->actual_duration;
                $salaryInfos[$salary->date_id] = $salary->actual_calc_duration;
                $salaryMode = $salary->salary_mode;
            }
            // 循环一个月的时间
            $salaryData = [];
            for ($d = $startDay; $d <= $endDay; $d++) {
                $tmp = '-';
                if (isset($salaryInfos[$d])) {
                    $tmp = $salaryInfos[$d];
                }
                $salaryData[] = $tmp;
            }
            // 组装所有数据
            $item = [];
            if (isset($personData[$personId])) {
                $item = $personData[$personId];
            } else {
                $item = [
                    '-',
                    '-',
                    '-',
                    '-',
                    '-',
                    '-',
                    '-',
                ];
            }
            $item[] = $g['depart_name'];
            $item[] = $g['job_name'];

            $unit = '小时';
            $unit1 = '小时';
            if ($salaryMode == 'day') {
                $unit = '天';
            } else if ($salaryMode == 'stage') {
                $unit = '场';
                $unit1 = '场';
            }

            $day = 1; 
            foreach ($salaryData as $s) {
                if ($s == '-') {
                    $item[] = $s;
                } else {
                    $item[] = $s . "" . $unit;
                }
                $day++;
            }


            $item[] = $totalActualDuration . "" . $unit;
            $item[] = $totalAdded1Fee;
            $item[] = $totalAdded2Fee;
            $item[] = $totalRoadFee;

            $item[] = $totalSeviceFee;
            $item[] = $totalRewardMonth;
            $item[] = $totalSalaryTotal;

            

            $items[] = $item;
        }

        $savePath = '/uploads/export/'.date('Ymd') ;
        $filename =  $month .'(人员薪酬)_' . uniqid() .'.xlsx';
        $filePath = ROOT_PATH . 'public' . $savePath;
        $fileSaveName =  $filePath  . '/' . $filename;
        if (!is_dir($filePath)) {
            @mkdir($filePath, 0755, true);
        }
        $headers = [
            '劳务公司',
            '人员类别',
            '姓名',
            '联系电话',
            '身份证号',
            '开户行名称',
            '银行卡号',
            '所属部门',
            '岗位',


            '1号',
            '2号',
            '3号',
            '4号',
            '5号',
            '6号',

            '7号',
            '8号',
            '9号',
            '10号',
            '11号',
            '12号',

            '13号',
            '14号',
            '15号',
            '16号',
            '17号',
            '18号',

            '19号',
            '20号',
            '21号',
            '22号',
            '23号',
            '24号',


            '25号',
            '26号',
            '27号',
            '28号',
        ];
        if ($lastDay >= 29) {
            $headers[] = '29号';
        }
        if ($lastDay >= 30) {
            $headers[] = '30号';
        }
        if ($lastDay >= 31) {
            $headers[] = '31号';
        }

        $headers[] = '实际出勤天数/小时数/场次';
        $headers[] = '餐补';
        $headers[] = '补助';
        $headers[] = '路费';
        $headers[] = '服务费（自招人员）';
        $headers[] = '激励补贴';
        $headers[] = '应发总金额';
        $exportLib = new ExportLib($headers, $items, $fileSaveName, 'save');
        $exportLib->createTable();
        $this->success('导出成功', '', ['file' => cdnurl($savePath . '/' .$filename, true)]);
    
    }

    private function calSalary($d)
    {
        $logPre = 'cal person salary by update';
        if (!$this->salaryInfo) {
            Log::write($logPre . ': 无对应当天的薪酬信息');
        } else {
            $this->salaryLib->setObject($this->personInfo, null, null, $this->salaryInfo);
            // 有打卡记录的才计算
            if (!empty($d->clock_json)) {
                $clockJson = json_decode($d->clock_json, true);  
                // 取出薪酬记录表中的岗位计算模式
                $salaryMode = $this->salaryInfo->salary_mode;
                // 如果是场次，需要有输入场次数字段才计算薪酬
                if ($salaryMode == 'stage' && isset($clockJson['stage'])) {
                    $calClock = $this->salaryLib->calStage($clockJson, $salaryMode);
                    $salaryPayable = $this->salaryLib->calSalary($calClock, $salaryMode);
                    $salaryRes = $this->salaryLib->calSalary($calClock, $salaryMode);
                    $salaryPayable = $salaryRes[0];
                    $added1Fee = $this->salaryLib->checkAdde1Fee($calClock);
                    $roadFee = $d->road_fee;
                    $salaryTotal = $salaryPayable + $added1Fee + $roadFee + $this->salaryInfo->added2_fee + $this->salaryInfo->self_sevice_fee + $this->salaryInfo->reward_month;

                    $this->salaryInfo->salary = $salaryRes[1];
                    $this->salaryInfo->clock_in = $calClock['clock_in']; 
                    $this->salaryInfo->clock_out = $calClock['clock_out']; 
                    $this->salaryInfo->added1_fee = $added1Fee;
                    $this->salaryInfo->road_fee = $roadFee;
                    $this->salaryInfo->salary_payable = $salaryPayable;
                    $this->salaryInfo->actual_duration =  $calClock['actual_duration'];
                    $this->salaryInfo->actual_calc_duration = $calClock['actual_calc_duration'];
                    $this->salaryInfo->salary_total = $salaryTotal;
                    // 更新用户的累积场次
                    $this->personInfo->explain_total = $this->personInfo->explain_total + $clockJson['stage'];
                    $this->personInfo->save();
                                
                    Log::write($logPre . ': 计算人员薪资完成, duty id =>' . $d->id . ', person_id =>' . $d->pt_person_id);
                } else if ($salaryMode != 'stage' && count($clockJson) >= 2) {
                    // 非场次必须有两次打卡记录
                    $calClock = $this->salaryLib->calClock($clockJson, $salaryMode, $d);
                    $salaryRes = $this->salaryLib->calSalary($calClock, $salaryMode);
                    $salaryPayable = $salaryRes[0];
                    $added1Fee = $this->salaryLib->checkAdde1Fee($calClock);
                    $roadFee = $d->road_fee;
                    $salaryTotal = $salaryPayable + $added1Fee + $roadFee + $this->salaryInfo->added2_fee + $this->salaryInfo->self_sevice_fee + $this->salaryInfo->reward_month;

                    $this->salaryInfo->clock_in = $calClock['clock_in']; 
                    $this->salaryInfo->clock_out = $calClock['clock_out']; 
                    $this->salaryInfo->added1_fee = $added1Fee;
                    $this->salaryInfo->road_fee = $roadFee;
                    $this->salaryInfo->salary_payable = $salaryPayable;
                    $this->salaryInfo->actual_duration =  $calClock['actual_duration'];
                    $this->salaryInfo->actual_calc_duration = $calClock['actual_calc_duration'];
                    $this->salaryInfo->salary_total = $salaryTotal;
                    Log::write($logPre . ': 计算人员薪资完成, duty id =>' . $d->id . ', person_id =>' . $d->pt_person_id);
                } else {
                    // $this->salaryInfo->clock_in = $clockJson[0];
                    // 其他的都不能计算薪酬
                    Log::write($logPre . ': 不满足计薪打卡条件, duty id =>' . $d->id);
                }
            }                
            $this->salaryInfo->is_cal = 1;
            $this->salaryInfo->save();
        }
    
    }

}
